package com.xuhai.blog19.admin.controller;

import com.xuhai.blog19.admin.form.LoginForm;
import com.xuhai.blog19.admin.service.CodeService;
import com.xuhai.blog19.admin.service.ExpiresService;
import com.xuhai.blog19.admin.service.UserService;
import com.xuhai.blog19.common.utils.R;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author PangJunjie
 * @Date 2023/2/6/006
 */
@RestController
@RequestMapping("/admin")
public class LoginController extends AbstractBaseController {
    @Autowired
    private CodeService codeService;
    @Autowired
    private UserService userService;
    @Autowired
    private ExpiresService expiresService;

    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletResponse response, String uuid) throws IOException {
        /*设置输出流的头信息*/
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        /*根据验证码创建图片*/
        BufferedImage bi = codeService.getKaptcha(uuid);
        /*获取输出流*/
        ServletOutputStream out = response.getOutputStream();
        /*验证码写入输出流*/
        ImageIO.write(bi, "jpg", out);
        /*关闭流*/
        IOUtils.closeQuietly(out);
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginForm loginForm) {
        return userService.login(loginForm);
    }

    @PostMapping("/logout")
    public R logout() {
        expiresService.logout(getUserId());
        return R.ok();
    }

}
